package lv.solcraft.replication.server.model;

import net.sf.json.JSONObject;

import org.springframework.util.Assert;

import com.sleepycat.persist.model.KeyField;
import com.sleepycat.persist.model.Persistent;

@Persistent
public class OperId {

    @KeyField(1)
    private Long originSiteId;

    @KeyField(2)
    private Long originOperId;

    /**
     * For persistence only
     */
    @Deprecated
    protected OperId() {
    }

    public OperId(Long originSiteId, Long originOperId) {
        Assert.notNull(originSiteId, "Origin site id can not be null");
        Assert.notNull(originOperId, "Origin oper id can not be null");
        this.originSiteId = originSiteId;
        this.originOperId = originOperId;
    }

    public Long getOriginSiteId() {
        return originSiteId;
    }

    public Long getOriginOperId() {
        return originOperId;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((originOperId == null) ? 0 : originOperId.hashCode());
        result = prime * result + ((originSiteId == null) ? 0 : originSiteId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final OperId other = (OperId) obj;
        if (originOperId == null) {
            if (other.originOperId != null)
                return false;
        } else if (!originOperId.equals(other.originOperId))
            return false;
        if (originSiteId == null) {
            if (other.originSiteId != null)
                return false;
        } else if (!originSiteId.equals(other.originSiteId))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return originSiteId + ":" + originOperId;
    }

    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        json.put("originSiteId", originSiteId);
        json.put("originOperId", originOperId);
        return json;
    }

    public static OperId fromJSON(JSONObject json) {
        long originSiteId = json.getLong("originSiteId");
        long originOperId = json.getLong("originOperId");
        return new OperId(originSiteId, originOperId);
    }
}
